Skip to content

fix: support nested validation error paths in useForm - #890

Merged
Brooooooklyn merged 8 commits into
voidzero-dev:mainfrom
0froq:fix/form-nested-error-paths
Nov 25, 2026
Merged

Brooooooklyn merged 8 commits into
voidzero-dev:mainfrom
0froq:fix/form-nested-error-paths

Conversation

@0froq

@0froq 0froq commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

This description was drafted by an agent from the diff and the commands it ran. froQ🐸 has reviewed it.

Fixes #875

Description

useForm() now accepts and clears the dotted error keys that nested validators return, in React, Vue, Svelte and Solid.

The error map, setError() and clearErrors() are typed by a FormErrorPath union that walks the action body. profile.name and contacts.0.email are valid keys, while a field that does not exist is still a type error. Top-level keys stay in the union, so generic helpers with K extends keyof T & string keep compiling. Files, blobs, dates, maps, sets and branded strings count as one field. Where a recursive body type repeats, or past six segments, any nested path is accepted, so a body with several self references stays cheap to check.

Editing data clears only the errors of the values that changed, plus the errors of their parent fields. Errors on unchanged siblings stay, for example on other contacts, and a literal field named email.work is kept apart from email. clearErrors('profile') clears profile and every error below it.

Type change

FormErrors<T> is now keyed by nested paths. Inside a generic function, Partial<Record<keyof T & string, string>> is no longer assignable to FormState<T, ...>['errors']: TypeScript cannot prove the nested-path keys from a generic T. Type such a map as FormErrors<T>, which void/pages-client now exports. Concrete body types are not affected.

Test

  • clears only the errors of the fields a change touched in packages/{react,vue,svelte}/test/unit/use-form.test.ts and packages/solid/test/unit/form-errors.test.ts.
  • packages/svelte/test/unit/use-form.test.ts: keeps an error set for a field whose name contains a dot and preserves a separate literal dotted error when editing or clearing its prefix.
  • packages/solid/test/unit/form-errors.test.ts: keeps an untouched row error when clearing its parent array error.
  • packages/void/test/unit/form-presentation.test.ts: the shared helpers, including literal dotted fields and missing optional parents.
  • Type checks: checkNestedErrorPaths() in each adapter's typecheck file, and packages/void/test/unit/form-error-path.typecheck.ts for typos, leaf values, paths deeper than six segments, recursive bodies and all-optional child objects.

Validators report nested messages as dotted keys such as `profile.name` or
`contacts.0.email`. The error map, `setError()` and `clearErrors()` now take
those keys, so apps no longer need a cast to read or clear them.
Editing or replacing a parent object or array now clears the errors of the
fields below it, matching how editing a scalar clears that field's error.
Clearing a parent with `clearErrors()` does the same and keeps unrelated
errors.

Svelte snapshots the parent field when a handler reports a nested error,
because the parent is what changed in `data`.
@0froq

0froq commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator Author

👁️‍🗨️ Review this pull request with grouped, summarized diffs at:
👉 https://pulls.review/gh/voidzero-dev/void/890?from=0froq

raw result

💭 analyzed by openai-compatible/opencode-go/deepseek-v4.1-flash
🕰️ 2026-11-21 02:34 UTC
🔗 head 8f80909
🤖 automated by pulls.review

{
  "headSha": "8f80909bf4522271ad4e899bdd95b3730aba4b3b",
  "result": {
    "overallSummary": "`useForm()` only understood **top-level** body field names: a nested validator message like `profile.name` was neither typed (TS7053 when read) nor cleared when the parent value was replaced or `clearErrors('profile')` was called, so stale messages survived a fix. This PR makes error keys a `FormErrorPath` union derived from the action body, adds shared `isFormErrorWithin`/`omitFormErrors` helpers, and uses them in all four adapters so a replaced or cleared parent also drops the errors of its nested fields.",
    "groups": [
      {
        "key": "error-path-types",
        "label": "Nested error path types & helpers",
        "summary": "Foundation of the fix: `FormErrorPath` walks the action body as a dotted template-literal union (including numeric array segments) and replaces `keyof TData` in `FormErrors`, `setError()` and `clearErrors()`. Two pure helpers, `isFormErrorWithin` and `omitFormErrors`, encode \"this key belongs to that field\" so every adapter clears parents and children the same way.",
        "category": "core",
        "filePaths": [
          "packages/void/src/pages/form-presentation.ts",
          "packages/void/src/pages/client.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/void/src/pages/form-presentation.ts",
            "text": "Public type change: existing consumers that index `errors` with a plain `string` may now see stricter typing, since the record keys are a union rather than `keyof TData & string`."
          }
        ],
        "lineNotes": [
          {
            "path": "packages/void/src/pages/form-presentation.ts",
            "side": "additions",
            "line": 27,
            "text": "Recursion stops by resolving to `never` at depth 6, so a body nested deeper than that silently loses its nested error keys instead of producing an expensive or infinite type."
          },
          {
            "path": "packages/void/src/pages/form-presentation.ts",
            "side": "additions",
            "line": 30,
            "text": "Array segments are typed as `` `${number}` ``, so `contacts.0.email` is accepted but so is an out-of-range `contacts.99.email` — indices are not checked against the tuple length."
          },
          {
            "path": "packages/void/src/pages/form-presentation.ts",
            "side": "additions",
            "line": 94,
            "text": "Returning the *same* object when nothing matched is load-bearing: React's `setErrorEdits` compares by reference to skip a state update."
          }
        ]
      },
      {
        "key": "adapter-clearing",
        "label": "Adapters clear nested errors",
        "summary": "Wires the shared helpers into each framework adapter so editing a scalar or replacing a parent value drops every error key below it, and `clearErrors(field)` also clears nested keys. React and Solid delegate to `omitFormErrors`; Vue and Svelte mutate the existing error map in place, as their `'in-place'` editing idiom requires.",
        "category": "core",
        "filePaths": [
          "packages/react/src/runtime/use-form.ts",
          "packages/vue/src/runtime/use-form.ts",
          "packages/svelte/src/runtime/use-form.svelte.ts",
          "packages/solid/src/runtime/use-form.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/svelte/src/runtime/use-form.svelte.ts",
            "text": "Input handlers report a nested error before the change effect runs, so `snapshotField()` now snapshots the *parent* field (`field.split('.')[0]`) — the value that actually changes in `data` — otherwise the parent change is re-detected and the freshly set nested error is cleared again."
          }
        ],
        "lineNotes": [
          {
            "path": "packages/react/src/runtime/use-form.ts",
            "side": "additions",
            "line": 205,
            "text": "The early-return condition changed from `!(field in current)` to a reference check on `omitFormErrors`: previously `clearErrors`/edit of `profile` returned early when only `profile.name` existed, which is exactly the bug being fixed."
          }
        ]
      },
      {
        "key": "tests",
        "label": "Regression & type tests",
        "summary": "One runtime case per adapter sets `profile.name` and `contacts.0.email`, replaces/clears the parents, and asserts only the unrelated error remains; four `checkNestedErrorPaths()` typecheck functions pin the nested keys as readable and clearable while `profile.missing` and `contacts.first` stay rejected inside `@ts-expect-error`.",
        "category": "tests",
        "filePaths": [
          "packages/react/test/unit/use-form.test.ts",
          "packages/react/test/unit/use-form.typecheck.ts",
          "packages/vue/test/unit/use-form.test.ts",
          "packages/vue/test/unit/form-errors.typecheck.ts",
          "packages/svelte/test/unit/use-form.test.ts",
          "packages/svelte/test/unit/form-errors.typecheck.ts",
          "packages/solid/test/unit/form-errors.test.ts",
          "packages/solid/test/unit/form-errors.typecheck.ts"
        ],
        "fileNotes": [
          {
            "path": "packages/solid/test/unit/form-errors.test.ts",
            "text": "`createForm()` gained `server`/`defaults` parameters with backwards-compatible defaults so the new case can seed nested server errors without a second fixture."
          },
          {
            "path": "packages/svelte/test/unit/use-form.test.ts",
            "text": "Cases call `svelte.flushSync()` between edits because the error clearing runs in an effect, not synchronously in the setter."
          }
        ]
      },
      {
        "key": "docs",
        "label": "Docs for nested error paths",
        "summary": "Updates the API table and the `setError()` guidance to say error keys can be dotted nested paths and that editing or clearing a parent field also clears the errors of its nested fields.",
        "category": "docs",
        "filePaths": [
          "docs/guide/pages-routing/actions-and-forms.md"
        ]
      }
    ],
    "schemaVersion": 1,
    "source": "llm",
    "generatedAt": "2026-11-21T02:34:06.868Z",
    "model": "openai-compatible/opencode-go/deepseek-v4.1-flash",
    "locale": "en"
  }
}

@cpojer

cpojer commented Nov 22, 2026

Copy link
Copy Markdown
Member

Thanks! It looks like there are a few issues still. Here is a slop review:

  • P2 The new path type breaks existing generic helpers. With K extends keyof T & string, TypeScript now rejects form.errors[field], setError(field, ...), and clearErrors(field). Keep top-level keys available to generic callers. Shared form types
  • P2 Editing one contact’s email clears validation errors on unchanged contacts in Vue and Svelte. Svelte also drops a freshly set error for a literal field named email.work. Both regressions reproduced against the base. All 65 existing adapter tests passed. Vue watcher · Svelte effect

@0froq

0froq commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator Author

Thank you! For the second one I'd rather fix the semantics than the prefix check in each adapter.

For the types, I'll keep top-level keys in the union: FormErrorPath<T> | (keyof T & string). That keeps K extends keyof T & string compiling while unknown nested paths are still rejected.

For clearing, I want one shared helper that diffs the previous and next value and returns the leaf paths that actually changed, used by all four adapters. Editing contacts.1.email then clears only that error, and replacing an array in React or Solid no longer wipes the other contacts. It also stops treating a literal email.work field as nested under email, since the paths come from the diff instead of a string prefix.

One assertion in the new tests will change. Replacing a parent only clears the leaves that changed, so I'll add cases for sibling errors and the dotted field name.

0froq and others added 3 commits November 23, 2026 08:11
The nested path union is a deferred conditional for an unresolved type parameter, so generic helpers keyed by `keyof T & string` no longer indexed the error map.
@cpojer

cpojer commented Nov 23, 2026

Copy link
Copy Markdown
Member

Assigning Partial<Record<keyof T & string, string>> to FormState<T, 'in-place'>['errors'] fails with TS2322 in the PR.

@0froq
0froq force-pushed the fix/form-nested-error-paths branch from 0e9b24f to 9f3cf5c Compare November 23, 2026 17:52
@0froq

0froq commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

There are only two shapes here, and it's a trade-off. Now it keeps exact nested keys, and a wrapper holding an error map types it as FormErrors<T>. The other needs a dotted index signature, which accepts Partial<Record<keyof T & string, string>> but stops rejecting a misspelled nested key and also stops accepting Record<string, string>. :(

@Brooooooklyn
Brooooooklyn self-requested a review November 25, 2026 09:51
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T10:35:47.474617Z 1fac745 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

# Conflicts:
#	packages/react/src/runtime/use-form.ts
#	packages/solid/src/runtime/use-form.ts
#	packages/svelte/src/runtime/use-form.svelte.ts
#	packages/vue/src/runtime/use-form.ts
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 9f3cf5c2b5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- Stop walking a body type where it repeats an ancestor, and past six
  segments, by accepting any nested path there. A body with several
  self references no longer fails with TS2589, and deep validator keys
  such as `sections.0.rows.0.cells.0.value` are accepted.
- Treat files, blobs, dates, maps, sets and branded primitives as one
  field, so `avatar.size` or `email.length` are not error paths.
- Compare ancestors by identity, so an all-optional child object that
  only matches its parent keeps rejecting typos.
- Fix lint rules enabled on main since the branch was opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 1fac745594

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Brooooooklyn
Brooooooklyn merged commit 46c605f into voidzero-dev:main Nov 25, 2026
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

React useForm: nested validation error paths are rejected by types and survive parent updates

3 participants